<script setup lang="ts">
import { ref, onMounted,reactive } from "vue";
import {UseLibraryState} from '../library_state'
import {NewUser,try_post_new_user} from './user'
import { ElNotification  } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const new_reader=reactive<NewUser>({
    name:'',
    nickName:'',
    password:'',
    role:'Reader'
})

const rules = reactive<FormRules>({
  name:[{required:true,message:'姓名不得为空!'}],
  nickName:[{required:true,message:'昵称不得为空!'}],
  password:[{required:true,message:'密码不得为空!'}],
  })

const form_ref = ref<FormInstance>();
const reset_form = () => {
  if (!form_ref.value) {
    return;
  }
  form_ref.value.resetFields();
};

const submit = async () => {
  if (!form_ref.value) {
    return;
  }
  const is_ok = await form_ref.value.validate();
  if (!is_ok) {
    return
  }
  try {
    await try_post_new_user(new_reader)
    ElNotification({
        title:'Success',
        message:'添加新用户成功!',
        type:'success',
        duration:5000
    })
  form_ref.value?.resetFields();

  } catch (error) {
        ElNotification({
        title:'Error',
        message:'添加新用户失败!\n'+error,
        type:'error',
        duration:10000,
    })
  }
}


</script>

<template>
  <el-form
    label-position="right"
    label-width="100px"
    style="max-width: 460px"
    ref="form_ref"
    status-icon
    :model="new_reader"
    :rules="rules"
  >
    <el-form-item label="姓名" prop="name">
      <el-input v-model="new_reader.name" />
    </el-form-item>
    <el-form-item label="昵称" prop="nickName">
      <el-input v-model="new_reader.nickName" />
    </el-form-item>
    <el-form-item label="登录密码" prop="password">
      <el-input type="password" v-model="new_reader.password" />
    </el-form-item>
    <el-form-item>
      <el-button type="danger" @click="reset_form()">重置</el-button>
      <el-button type="primary" @click="submit()">确认</el-button>
    </el-form-item>
  </el-form>
</template>

<style>

</style>
